let fs = require("fs")
let pathApi = require("path")
let iconv = require('iconv-lite');
let baseUrl = "C:/Program Files (x86)/Steam/steamapps/common/Mount & Blade II Bannerlord"
let CNs = {}
// C:/Program Files (x86)/Steam/steamapps/common/Mount & Blade II Bannerlord/Modules/Native/ModuleData/Languages/CNs
let cnPath = pathApi.resolve(baseUrl,"./Modules/Native/ModuleData/Languages/CNs/std_crafting_pieces_xml-zho-CN.xml") 
// std_crafting_pieces_xml-zho-CN.xml
const METERIAL_ENUMS = {
    Iron6 : "精炼钢",
    Iron5 : "优质钢",
    Iron4 : "钢",
    Iron3 : "铁",
    Iron2 : "熟铁",
    Iron1 : "生铁",
    Wood: "木头"
}

fs.stat(cnPath,async err => {
    if(err) {
        console.log(err);
    } else {
        ParseCnXml(cnPath)
        let pieces = parsepieces(pathApi.resolve(baseUrl,"./Modules/Native/ModuleData/crafting_pieces.xml"))
        // { id: "", name:"" , material: {id, count}}
        ParseCnXml(pathApi.resolve(baseUrl,"./Modules/SandBoxCore/ModuleData/Languages/CNs/std_spitems_xml-zho-CN.xml") )
        let weapons = ParseWeapon(pathApi.resolve(baseUrl,"./Modules/SandBoxCore/ModuleData/items/weapons.xml"), pieces)
        fs.writeFileSync("./tmp.json", JSON.stringify(weapons))
    }
})



function ParseCnXml(path) {
    let buffer = fs.readFileSync(path);
    let text = iconv.decode(buffer,"utf-16");
    if(text) {
        text = text.match(/<string id=".+" text="[^"]+"\/>/g);
        text.forEach( v => {
            if(/<string id="(.+)" text="([^"]+)"\/>/.test(v)){
                CNs[RegExp.$1] = RegExp.$2
            }
        })
    }
}

function parsepieces (path) {
    let text = fs.readFileSync(path).toString()
    if(text) {
        text = text.match(/<CraftingPiece (?:(?!CraftingPiece)[\w\W])+<\/CraftingPiece>/g);
        let res = {}
        text.map(piece => {
            let ret = {}
            if(/id="([^"]+)"/.test(piece)){
                ret.id = RegExp.$1;
                res[ret.id] = ret
            }
            if(/name="{=([^}]+)}([^"]+)"/.test(piece)){
                ret.name = CNs[RegExp.$1] || RegExp.$2;
            }
            if(/<Material id="([^"]+)"\W+count="([^"]+)"/.test(piece)){
                ret.material = { id:RegExp.$1, count:RegExp.$2-0 }
            }
        })
        return res
    }
}

/**
 * <CraftedItem id="ridged_sabre_sword_t4"
               name="{=8fK5E68M}Ridged Saber "
               crafting_template="OneHandedSword"
               culture="Culture.aserai">
    <Pieces>
      <Piece id="khuzait_blade_8"
             Type="Blade"
             scale_factor="90" />
      <Piece id="empire_guard_1"
             Type="Guard"
             scale_factor="100" />
      <Piece id="khuzait_noble_grip_3"
             Type="Handle"
             scale_factor="100" />
      <Piece id="khuzait_noble_pommel_4"
             Type="Pommel"
             scale_factor="100" />
    </Pieces>
  </CraftedItem>
 * 
 */


function ParseWeapon (path, pp) {
    let text = fs.readFileSync(path).toString()
    if(text) {
        text = text.match(/<CraftedItem (?:(?!CraftedItem)[\w\W])+<\/CraftedItem>/g);
        text = text.filter(v => /<Pieces>/.test(v))
        
        text = text.map(piece => {
            let ret = {}
            if(/id="([^"]+)"/.test(piece)){
                ret.id = RegExp.$1;
            }
            if(/name="{=([^}]+)}([^"]+)"/.test(piece)){
                ret.name = CNs[RegExp.$1] || RegExp.$2;
            }
            if(/crafting_template="{=([^}]+)}([^"]+)"/.test(piece)){
                ret.crafting_template = RegExp.$1;
            }
            
            ret.pieces = piece.match(/<Piece[^>]+\/>/g)
            ret.materials = {}
            ret.materialsCNs = {}
            
            ret.pieces = ret.pieces.map(p => {
                let p2 = {}
                if(/id="([^"]+)"/.test(p)){
                    p2.id = RegExp.$1;
                    p2.info = pp[p2.id];
                    let {material} = p2.info;
                    if(material && material.id) {
                        if(ret.materials[material.id]) {
                            ret.materials[material.id] += material.count
                        } else {
                            ret.materials[material.id] = material.count
                            if(METERIAL_ENUMS[material.id]) {
                                ret.materialsCNs[METERIAL_ENUMS[material.id]] = ret.materials[material.id]
                            }
                        }
                    }
                }
                if(/scale_factor="([^"]+)"/.test(p)){
                    p2.scale_factor = RegExp.$1;
                }
                if(/Type="([^"]+)"/.test(p)){
                    p2.Type = RegExp.$1;
                }
                return p2
            })
            return ret
        })
        return text
    }
}



// CNPaths.forEach(path => {
//     let dirs = fs.readdirSync(path)
//     dirs.forEach(file => {
//         if(/\.xml$/.test(file)){
//             let buffer = fs.readFileSync(path + "/" + file);
//             let text = iconv.decode(buffer,"utf-16");
//             let ret = text;
//             if(ret) {
//                 ret = ret.match(/<string id=".+" text="[^"]+"\/>/g);
//                 ret.forEach( v => {
//                     if(/<string id="(.+)" text="([^"]+)"\/>/.test(v)){
//                         CNs[RegExp.$1] = RegExp.$2
//                     }
//                 })
//             }
//         }
//     })
// })


// // items文件
// let items = {}
// let itemPaths = ["../spitems"]
// itemPaths.forEach(dir => {
//     let dirs = fs.readdirSync(dir)
//     dirs.forEach(path => { 
//         path = dir + "/" + path;
//         let ret = fs.readFileSync(path).toString()
//         let arr = ret.match(/id="[^"]+"\n?\s+name="{=[^}]+}/g)
//         arr.forEach(function(item){
//             if(/id="(.+)"\n?\s+name="{=(.+)}$/.test(item)){
//                 items[`"${RegExp.$1}"`] = `"${CNs[RegExp.$2]}"`
//                 items[`"Item.${RegExp.$1}"`] = `"${CNs[RegExp.$2]}"`
//                 ret = ret.replace(new RegExp(`"${RegExp.$1}"`,"ig"), `"${CNs[RegExp.$2]}"`)
//             }
//         })
//         if(!fs.existsSync(pathApi.dirname(path) + "cn")){
//             fs.mkdirSync(pathApi.dirname(path) + "cn")
//         }
//         fs.writeFile(pathApi.dirname(path) + "cn/" + pathApi.basename(path), ret, function(err) {
//             if(err) {
//                 return;
//             }
//         });
//     })
// })

// // 人物
// let charactersPath = ["../spnpccharacters.xml"];
// charactersPath.forEach(path => {
//     let ret = fs.readFileSync(path).toString()
//     for (let key in CNs) {
//         ret = ret.replace(new RegExp( `{=${key}}`,"ig"), CNs[key])
//     }
//     for (let key in items) {
//         ret = ret.replace(new RegExp( key,"ig"), items[key])
//     }
//     if(!fs.existsSync(pathApi.dirname(path) + "/characterCn")){
//         fs.mkdirSync(pathApi.dirname(path) + "/characterCn")
//     }
//     fs.writeFile(pathApi.dirname(path) + "/characterCn/" + pathApi.basename(path), ret, function(err) {
//         if(err) {
//             return;
//         }
//     }); 
// })



